import { defineStore } from 'pinia';
import { getUserList, deleteUser, batchDeleteUsers,  searchUserByName } from '@/api';
import { ElMessage } from 'element-plus';

export const useUserManagementStore = defineStore('userManagement', {
  state() {
    return {
      users: [],
      loading: false,
      error: null,
    };
  },

  actions: {
    async fetchUsers(params = { page: 1, pageSize: 5 }) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await getUserList(params)
        console.log('API完整响应:', response);
        
        if (response.data.code === 200) {
          const { data } = response.data;
          this.users = data || [];
          return {
            total: data?.length || 0,
            list: this.users
          };
        } else {
          throw new Error(response.data.message || '获取用户数据失败');
        }
      } catch (err) {
        console.error('获取用户数据失败:', err);
        this.error = {
          message: '获取用户数据失败',
          details: err.message
        };
        return {
          total: 0,
          list: []
        };
      } finally {
        this.loading = false;
      }
    },

    async searchUser(params) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await searchUser({
          userId: params.userId.toString()
        });
        console.log('搜索响应:', response);
        
        if (response.data.code === 200) {
          const { data } = response.data;
          const userList = Array.isArray(data) ? data : (data ? [data] : []);
          this.users = userList;
          return {
            total: userList.length,
            list: this.users
          };
        } else {
          throw new Error(response.data.status || response.data.message || '搜索用户失败');
        }
      } catch (err) {
        console.error('搜索用户失败:', err);
        const errorMessage = err.response?.data?.status || err.message;
        this.error = {
          message: '搜索用户失败',
          details: errorMessage
        };
        ElMessage.error(errorMessage);
        return {
          total: 0,
          list: []
        };
      } finally {
        this.loading = false;
      }
    },

    async searchUserByName(params) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await searchUserByName({
          name: params.name
        });
        
        if (response.data.code === 200) {
          const { data } = response.data;
          const userList = Array.isArray(data) ? data : (data ? [data] : []);
          this.users = userList;
          return {
            total: userList.length,
            list: this.users
          };
        } else {
          throw new Error(response.data.status || response.data.message || '搜索用户失败');
        }
      } catch (err) {
        console.error('搜索用户失败:', err);
        const errorMessage = err.response?.data?.status || err.message;
        this.error = {
          message: '搜索用户失败',
          details: errorMessage
        };
        ElMessage.error(errorMessage);
        return {
          total: 0,
          list: []
        };
      } finally {
        this.loading = false;
      }
    },

    async deleteUser(userId) {
      try {
        console.log('删除单个用户:', userId);
        const response = await deleteUser(userId);
        console.log('删除响应:', response);
        
        if (response.data.code === 200 ||response.data.code === 500) {
          this.users = this.users.filter(user => user.userId !== userId);
          ElMessage.success('删除成功');
          return true;
        } else if (response.data.code === 500 && response.data.msg.includes('找不到')) {
          // 处理找不到用户的情况
          ElMessage.warning('找不到该用户');
          return false;
        } else {
          throw new Error(response.data.msg || '删除用户失败');
        }
      } catch (err) {
        console.error('删除失败:', err);
        const errorMessage = err.response?.data?.msg || err.message;
        this.error = {
          message: '删除用户失败',
          details: errorMessage
        };
        ElMessage.error(errorMessage);
        return false;
      }
    },

    async batchDeleteUsers(userIds) {
      try {
        console.log('准备批量删除的用户IDs:', userIds);
        const response = await batchDeleteUsers(userIds);
        console.log('批量删除响应:', response);
        
        if (response.data.code === 200||response.data.code === 500) {
          this.users = this.users.filter(user => !userIds.includes(user.userId));
          ElMessage.success('批量删除成功');
          return true;
        } else if (response.data.code === 500 && response.data.msg.includes('找不到')) {
          // 处理找不到用户的情况
          ElMessage.warning('部分或全部用户不存在');
          await this.fetchUsers({ page: 1, pageSize: this.users.length }); // 刷新用户列表
          return false;
        } else {
          throw new Error(response.data.msg || '批量删除失败');
        }
      } catch (err) {
        console.error('批量删除失败:', err);
        const errorMessage = err.response?.data?.msg || err.message;
        this.error = {
          message: '批量删除用户失败',
          details: errorMessage
        };
        ElMessage.error(errorMessage);
        return false;
      }
    },
  },
});
